package com.flyfinger.rpcserver.lagou.handler;

import com.flyfinger.pojo.RpcRequest;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
@Component
@ChannelHandler.Sharable
public class UserServiceHandler extends ChannelInboundHandlerAdapter implements BeanFactoryAware {

	private BeanFactory beanFactory;

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		final RpcRequest rpcRequest;
		if (!(msg instanceof RpcRequest)) {
			System.out.println("未获取到RpcRequest");
			return;
		}
		rpcRequest = (RpcRequest) msg;
		System.out.println(String.format("服务端[%s]获取到RpcRequest：[%s]", getPort(), rpcRequest));

		final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		final Class<?> aClass = classLoader.loadClass(rpcRequest.getClassName());
		final Object bean = beanFactory.getBean(aClass);

		final Method method = aClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
		final Object invoke = method.invoke(bean, rpcRequest.getParameters());

		rpcRequest.setResult(String.format("来自[%s]机器的消息反馈:[%s]", getPort(), invoke));

		System.out.printf("服务端[%s]调用[%s]方法成功，返回值为[%s]", getPort(), rpcRequest.getMethodName(), rpcRequest);
		ctx.writeAndFlush(rpcRequest);
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}

	public BeanFactory getBeanFactory() {
		return beanFactory;
	}

	private int port;

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}
}
